var util = require("../../utils/util.js");
// pages/order/order.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isShowFreight: !1,
        showTipAddress: !0,
        maxStock: 99,
        isSubmit: false, //防止表单重新提交
        coupon: {
            price: 0.00,
            totalLength: 0,
            canUseCoupons: [],
            noCanUseCoupons: []
        },
        vouchers: {
            price: 0.00,
            totalLength: 0,
            canUseVouchers: [],
            noCanUseVouchers: []
        },
        defaultTime: util.addDate(3).getTime(),
        addressList: [],
        onceTimesDiscount: 0.00,
        totalDiscount: 0.00,
        actualTotal: 0,
        total: 0,
        totalCount: 0,
        transfee: 0,
        reduceAmount: 0,
        remark: "",
        couponIds: []

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        //获取订单数据
        this.loadOrderData();
        if(options.inPurchase){
            this.setData({
                inPurchase:true,
            })
        }
        //获取地址
        //this.getDefaultAddress();

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {},
    getDefaultAddress: function() {
        let _this = this;
        const openid = wx.getStorageSync('openid');
        var len = this.data.orderItem.finallyDistributionTimes || 1;
        util.request(getApp().api.address.default+'?openid=' + openid).then(
            function(res) {
                if (res.code == 200) {
                    if (res.data.length == 0) {
                        _this.setData({
                            addressList: [],
                        })
                    } else {
                        let addressTemp = JSON.parse(JSON.stringify(res.data[0]));
                        let time = util.addDate(3).getTime();
                        addressTemp.distributionTime = time;
                        res.data[0].distributionTime = time;
                        if (_this.data.orderItem.finallyDistributionTimes == 1) {
                            res.data[0].num = _this.data.orderItem.productNum
                        } else {
                            res.data[0].num = 1;
                        }
                        addressTemp.num = 1;
                        _this.setData({
                            addressTemp: addressTemp,
                            addressList: [res.data[0]]
                        })
                    }
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                    return false;
                }

            }
        )
    },
    removeFromList: function(e) {
        let index = e.currentTarget.dataset.index;
        var list = JSON.parse(JSON.stringify(this.data.addressList));
        if (this.data.addressList.length <= 1) {
            wx.showToast({
                title: "不能再删除该地址了",
                icon: "none", //图标,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });

            setTimeout(function() {
                wx.hideToast();
            }, 1500);
        } else {
            list.splice(index, 1);
            this.setData({
                addressList: list
            })
        }
    },
    addToList: function(e) {
        let arr = this.data.addressList;
        let index = ~~e.currentTarget.dataset.index;
        if (this.data.addressList.length >= this.data.orderItem.finallyDistributionTimes) {
            wx.showToast({
                title: "不能再增加地址了",
                icon: "none", //图标,
                mask: false, //显示透明蒙层，防止触摸穿透,
            });
            setTimeout(function() {
                wx.hideToast();
            }, 1500);
        } else {
            arr.push({});
            this.setData({
                addressList: arr
            })
        }
        wx.navigateTo({
            url: "/pages/select-address/select-address?addressIndex=" + (index+1) + '&count=' + this.data.orderItem.finallyDistributionTimes
        })
    },
    toAddress: function(e) {
        let info = e.currentTarget.dataset.info || {};
        let index = ~~e.currentTarget.dataset.index;
        wx.navigateTo({
            url: "/pages/select-address/select-address?addressIndex=" + index + '&id=' + info.id+ '&count=' + this.data.orderItem.finallyDistributionTimes
        })
    },
    loadOrderData: function() {
        var addrId = 0;
        if (this.data.addressInfo != null) {
            addrId = this.data.addressInfo.addrId;
        }

        wx.showLoading({
            mask: true
        });
        let orderItem = JSON.parse(wx.getStorageSync("orderItem"));

        this.setData({
            orderItem: orderItem,
            number: orderItem.productNum,
            totalMoney: orderItem.money
        });

        this.getGoodsDetail(orderItem.productId);
        this.getDiscount(orderItem.productId);

    },
    getGoodsDetail: function(e) {
        const _this = this;
        util.request(getApp().api.goods.detail, { productId: e }).then(
            function(res) {
                if (res.code == 200) {
                    let goods = res.data[0];
                    goods.sellPrice = goods.sellPrice / 100;
                    goods.trackFee = goods.trackFee / 100;
                    _this.setData({
                        goods: goods
                    });
                    if (_this.data.maxStock < _this.data.number) {
                        _this.setData({
                            number: _this.data.maxStock //弹窗里面的+-数值
                        })
                    }
                    //内部价格
                    if (_this.data.inPurchase) {
                        _this.setData({
                            inPurchaseDiscount: goods.sellPrice - _this.data.orderItem.money
                        });
                    }
                    //获取商品信息
                    _this.calc();
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                }
            }
        );
    },
    toDelivery: function(e) {
        let index = e.currentTarget.dataset.index;
        if (this.data.orderItem.finallyDistributionTimes != 1) {
            wx.navigateTo({
                url: "/pages/delivery-ordertime/delivery-ordertime?index=" + index
            })
        }
    },
    showFreightRule: function() {
        this.setData({
            isShowFreight: !0
        })
    },
    closeFreight: function() {
        this.setData({
            isShowFreight: !1
        })
    },
    openAdress: function() {
        this.setData({
            showTipAddress: !0
        })
    },
    closeAdress: function() {
        this.setData({
            showTipAddress: !1
        })
    },
    changeData: function() {
    },
    toPay: function() {
        let addrList =JSON.parse(JSON.stringify(this.data.addressList));
        if (!this.data.addressList[0]) {
            wx.showToast({
                title: '请选择地址',
                icon: "none"
            });
            return false;
        }
        if(this.data.orderItem.finallyDistributionTimes > 1){
            if(this.data.number<= this.data.orderItem.finallyDistributionTimes){
                wx.showToast({
                    title: "您还有"+ (this.data.orderItem.finallyDistributionTimes- this.data.addressList.length)+"次机会需要购水", //提示的内容,
                    icon: "none", //图标,
                    mask: false, //显示透明蒙层，防止触摸穿透,
                });
                setTimeout(function() {
                    wx.hideToast();
                }, 1500);
                return false;
            }
            let left= this.totalNum(this.data.addressList,this.data.addressList.length-1,this.data.number);
            if(left>0){
                wx.showToast({
                    title: "您还有"+ left +"箱水需要选择配送地点和配送时间", //提示的内容,
                    icon: "none", //图标,
                    mask: false, //显示透明蒙层，防止触摸穿透,
                });
                setTimeout(function() {
                    wx.hideToast();
                }, 1500);
                return false;
            }
        }else{
            addrList[0].distributionTime = util.addDate(3).getTime();
            addrList[0].num = this.data.number;
        }
        
        let _this = this;
        if (_this.data.isSubmit) {
            return false
        } else {
            _this.setData({
                isSubmit: true
            });
            const openid = wx.getStorageSync('openid');
            var data = {
                orderType: _this.data.inPurchase?6:0,
                productNum: _this.data.number,
                baseId: _this.data.orderItem.productId,
                openId: openid,
                discountCoupon: _this.data.coupon.id ? _this.data.coupon.id : '',
                cashCoupon: _this.data.vouchers.id ? _this.data.vouchers.id : '',
                orderAmount: _this.data.totalMoney * 100,
                productHeft: (~~_this.data.orderItem.selectWeight * ~~_this.data.number) * 1000,
                freight: _this.data.totalFreight * 100,
                address: addrList,
                deliveryNum: _this.data.orderItem.finallyDistributionTimes,
            };

            util.post(
                getApp().api.wxpay.pay,
                data
            ).then(
                function(res) {
                    _this.setData({
                        isSubmit: false
                    });
                    if (res.code == 200) {
                        wx.requestPayment({
                            timeStamp: res.timeStamp,
                            nonceStr: res.nonceStr,
                            package: res.package,
                            signType: res.signType,
                            paySign: res.paySign,
                            success: function(t) {},
                            fail: function(t) {},
                            complete: function(t) {
                                if ("requestPayment:fail" != t.errMsg && "requestPayment:fail cancel" != t.errMsg) {
                                    wx.redirectTo({
                                        url: "/pages/pay-suc/pay-suc?goodsId=" + _this.data.orderItem.productId+ '&type=' + (_this.data.inPurchase?6:1)
                                    })
                                } else {
                                    wx.showModal({
                                        title: "提示",
                                        content: "订单尚未支付",
                                        showCancel: !1,
                                        confirmText: "确认",
                                        success: function(t) {
                                            t.confirm && wx.redirectTo({
                                                // url: "/pages/order-list/order-list?id=1"
                                                url: "/pages/pay-suc/pay-suc?goodsId=" + _this.data.orderItem.productId + '&type=' + (_this.data.inPurchase?6:1)
                                            });
                                        }
                                    });
                                }
                            }
                        })
                    } else {
                        wx.showToast({
                            title: res.msg, //提示的内容,
                            icon: "none", //图标,
                            //duration: 1500, //延迟时间,
                            mask: false, //显示透明蒙层，防止触摸穿透,
                        });
                        setTimeout(function() {
                            wx.hideToast();
                        }, 1500);
                        return
                    }
                },
                function() {
                    _this.setData({
                        isSubmit: false
                    });
                }
            )
        }
    },
    numberSub: function() {
        if(this.data.orderItem.finallyDistributionTimes > 1){
            if(this.data.number<= this.data.orderItem.finallyDistributionTimes){
                wx.showToast({
                    title: "您还有"+ (this.data.orderItem.finallyDistributionTimes- this.data.addressList.length)+"次机会需要购水", //提示的内容,
                    icon: "none", //图标,
                    mask: false, //显示透明蒙层，防止触摸穿透,
                });
                setTimeout(function() {
                    wx.hideToast();
                }, 1500);
                return false
            }
        }

        this.setData({
            number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
        });
        this.setData({
            ['orderItem.productNum']:this.data.number
        });
        wx.setStorageSync('orderItem',JSON.stringify(this.data.orderItem));
        this.getDiscount(this.data.orderItem.productId);
    },
    numberAdd: function() {
        this.setData({
            number: this.data.number + 1 <= this.data.maxStock ? this.data.number + 1 : this.data.maxStock,
        });
        this.setData({
            ['orderItem.productNum']:this.data.number
        });
        wx.setStorageSync('orderItem',JSON.stringify(this.data.orderItem));
        this.getDiscount(this.data.orderItem.productId);
    },
    numberBlur: function(e) {

        var num = ~~e.detail.value;
        if (num <= 0) num = 1;
        if (this.data.maxStock && (num > this.data.maxStock)) num = this.data.maxStock;
        if(this.data.orderItem.finallyDistributionTimes > 1){
            if(this.data.number<= this.data.orderItem.finallyDistributionTimes){
                wx.showToast({
                    title: "您还有"+ (this.data.orderItem.finallyDistributionTimes- this.data.addressList.length)+"次机会需要购水", //提示的内容,
                    icon: "none", //图标,
                    mask: false, //显示透明蒙层，防止触摸穿透,
                });
                setTimeout(function() {
                    wx.hideToast();
                }, 1500);
                return false;
            }
        }
        this.setData({ number: num });
        this.setData({
            ['orderItem.productNum']:this.data.number
        });
        wx.setStorageSync('orderItem',JSON.stringify(this.data.orderItem));
        this.getDiscount(this.data.orderItem.productId);
    },
    calc: function(e) {

        let onceTimesDiscount = this.data.onceTimesDiscount;
        let inPurchaseDiscount = 0;
        if(this.data.inPurchase){
            inPurchaseDiscount = this.data.inPurchaseDiscount * this.data.number;
        }
        let totalDiscount = 0;
        let totalFreight = 0;
        if (this.data.orderItem.finallyDistributionTimes == 1) {
            totalDiscount = ~~this.data.vouchers.price + ~~this.data.coupon.price + ~~onceTimesDiscount ;
            totalFreight = this.onceFreightCalculationFormula(this.data.number, this.data.orderItem.selectWeight);
            if(this.data.inPurchase){
                totalDiscount = inPurchaseDiscount*100
            }
        } else {
            totalDiscount = this.data.vouchers.price + this.data.coupon.price;
            totalFreight = this.moreFrightCalculationFormula(this.data.number, this.data.orderItem.selectWeight, this.data.orderItem.finallyDistributionTimes, this.data.orderItem.trackFee)
        }
        this.setData({
            totalDiscount: totalDiscount / 100,
            totalFreight: totalFreight,
            totalMoney: this.data.goods.sellPrice * this.data.number - totalDiscount / 100 + totalFreight
        });
    },
    /**
     * 单次价格配送计算公式 (虽然可以合并，以防需求变化 还是分开来写)
     */
    onceFreightCalculationFormula: function(num, weight) {
//        if (weight * num <= 20) {
            return 0
//        } else {
//           return (Math.ceil(+weight * num) - 20) * 1
//        }
    },
    /**
     * 多次价格配送计算公式(虽然可以合并，以防需求变化 还是分开来写)
     */
    moreFrightCalculationFormula: function(num, weight, times, trackFee) {
        return (times - 1) * 50
    },
    //获取优惠
    getDiscount: function(e) {
        const _this = this;
        util.request(getApp().api.coupon.default, { baseId: e, num: _this.data.number }).then(
            function(res) {
                if (res.code == 200) {
                    if (res.data != null) {
                        if (res.data.type == '0') {
                            _this.setData({
                                coupon: res.data || { price: 0.00 }
                            })
                        } else {
                            _this.setData({
                                vouchers: res.data || { price: 0.00 }
                            })
                        }
                    }
                    _this.calc();
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                }
            }
        );
    },
    toCoupon: function() {
        wx.navigateTo({
            url: "/pages/coupon/coupon?baseId=" + this.data.orderItem.productId + '&num=' + this.data.number
        })
    },
    toVoucher: function() {
        wx.navigateTo({
            url: "/pages/voucher/voucher?baseId=" + this.data.orderItem.productId + '&num=' + this.data.number
        })
    },
    /**
     * 计算剩余多少箱水
     */
    getSum: function(total, obj){
        obj.num =obj.num || 0;
        return total + obj.num;
    },
    /**
     * 计算剩余多少箱水
     */
    totalNum: function(arr, index, all){
        let _this = this;
        var array = arr.slice(0, index + 1);
        if(!array[0].num){
            return all;
        }else{
            var left = all - array.reduce(_this.getSum, 0)
            if (left < 0) {
                return 0;
            } else {
                return all - array.reduce(_this.getSum, 0);
            }
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    }
});